package com.sesame.service;

import com.sesame.api.FMSConfig;
import kim.sesame.framework.entity.GMap;
import kim.sesame.framework.utils.GData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Service
public class NodeService {

    @Autowired
    private FMSConfig fmsConfig;

    public List<GMap> queryNodes(String path) {
        File file = new File(path);
        return searchfile(file, null);
    }

    private List<GMap> searchfile(File file, String parentId) {
        List<GMap> listAll = new ArrayList<GMap>();
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            File f = files[i];

            String path = f.getAbsolutePath();
            String id = path.hashCode() + "";

            GMap map = GMap.newMap();
            map.putAction("id", id);
            map.putAction("parentId", parentId);
            map.putAction("title", f.getName());

            GMap data = GMap.newMap();
            data.putAction("path", path);
            data.putAction("src", path.replace(fmsConfig.getFilePath(), fmsConfig.getMapping()));
            data.putAction("size", f.length() / 1024);
            map.putAction("basicData", data);

            if (f.isDirectory()) {
                List<GMap> list = searchfile(f, id);
                map.putAction("children", list);
            }
            listAll.add(map);
        }
        return listAll;
    }
}
